import api from "../../../common/api";
import locationBehavior from "../../../behaviors/location";
import {imBe} from "../../../behaviors/imBe";
import { setData } from "../../../models/transferData";
import { gioKeyuanLog, gioCloseLog, gioCooperationLog } from "../../../common/gioHandler";
const app = getApp();
Component({

  behaviors: [locationBehavior, imBe],
  /**
   * 组件的属性列表
   */
  properties: {
    cooperationId: { //房源id
      type: String,
      value: ''
    },
    userId: { //房源方id
      type: String,
      value: ''
    },
    
    unionid:{ //im聊天需要的参数
      type:String,
      value:''
    },
    type: { // 区别打电话和im聊天
      type: String,
      value: ''
    },
    winFrom:{ //gio---打开身份提交弹窗时触发---触发入口
      type: String,
      value: ''
    },
    


    // gio需要的参数--im打开IM聊天的上级页面
    PageFrom:{
      type:String,
      value:''
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    isShowVerifyWindow: false, //是否展示验证弹窗
    isShowVmPhone: false, //是否展示打电话弹窗
    lng: '', // 经度
    lat: '', //维度
    imgArr: [], // 验证弹窗的图片
    authCardInfo:{} //IM聊天需要的数据
  },

  /**
   * 组件的生命周期
   */
  lifetimes: {
    attached: function () {},
    detached: function () {},
  },

  /**
   * 组件的方法列表
   */
  methods: {
    onClickBut() {
      this.getWxLocationBe()
        .then((res) => {
          this.setData({
            lng: res.longitude,
            lat: res.latitude
          })
          this.checkInviterAuthWindow()
        })
        .catch(() => {
          this.checkInviterAuthWindow()
        })
    },
    checkInviterAuthWindow(){
      return new Promise((resolve, reject) => {
        if(this.data.type==='onLine'){ //发起im咨询埋点
          app.globalData.loginPromise.then(({ sessionUser }) => {
            gioCooperationLog('IM_click', sessionUser.id, this.data.winFrom);
          })
        } else { //发起电话咨询埋点
          app.globalData.loginPromise.then(({ sessionUser }) => {
            gioCooperationLog('cooperation_phone_click', sessionUser.id, this.data.winFrom);
          })
        }
      let {userId,lng,lat} = this.data
        api.checkInviterAuthWindow({toUserId: userId,lng,lat}, (res) => {
          if (res && res.data && res.data.isSuccess) {
            if (res.data.content && res.data.content.needWindow) { //出现验证弹窗
              let winFrom = this.data.winFrom
              let infromWay = this.data.type==='onLine'? 'IM':'虚拟号呼叫'
              gioKeyuanLog('informWinPop',winFrom,infromWay)
              let imgArr = res.data.content.imgList
              this.setData({
                isShowVerifyWindow: true,
                imgArr,
              })
            } else {
              if(res.data.content&& res.data.content.needAuth){ //是否开启认证
                this.getCardInfo().then(()=>{
                  if(this.data.type==='onLine'){ //有定位有验证 直接去im聊天
                    let unionid = this.data.unionid
                    let cooperationId = this.data.cooperationId
                    let agentId = this.data.userId
                    wx.navigateTo({
                      url: `/pages/im/imMessagelist/imMessagelist?unionid=${unionid}&cooperationId=${cooperationId}&agentId=${agentId}&ispop=0&pageFrom=${this.data.PageFrom}`
                    });
                  } else { //有定位有验证 直接出现打电话弹窗、
                    let options = {
                      cooperationId:this.data.cooperationId,
                      unionid: this.data.unionid,
                      ispop:'0',
                      agentId:this.data.userId
                    }
                    this.$sendAuthCard(options)
                    this.setData({
                      isShowVmPhone: true
                    })
                  }
                })
              } else {
                if(this.data.type==='onLine'){ //im聊天
                  let unionid = this.data.unionid
                  let cooperationId = this.data.cooperationId
                  let agentId = this.data.userId
                  wx.navigateTo({
                    url: `/pages/im/imMessagelist/imMessagelist?unionid=${unionid}&cooperationId=${cooperationId}&agentId=${agentId}&pageFrom=${this.data.PageFrom}`
                  });
                } else { //出现打电话弹窗
                  this.setData({
                    isShowVmPhone: true
                  })
                }
              }
            }
            resolve();
          } else {
            console.log('接口问题')
            reject()
          }
        });
      });
    },

    //关闭认证的弹窗
    closeVerifyWindow(e) {
      // 关闭弹窗的埋点
      let that = this
      if(e.detail.length!==0){
        that.data.imgArr = e.detail
      }
      let havePosition = (that.data.lng!==''&&that.data.lat!=='')? "允许位置授权" : "未允许位置授权"
      let haveJpg = (that.data.imgArr&&that.data.imgArr.length!==0)? "有名片图" : "无名片图"
      gioCloseLog('gioCloseLog',havePosition,haveJpg)
      wx.showModal({
        title: '温馨提示',
        content: '放弃提交身份验证将无法与对方正常沟通哦~是否选择放弃？',
        cancelText:'放弃提交',
        cancelColor:'#cccccc',
        confirmText:'取消',
        confirmColor:'#07C160',
        success (res) {
          if (res.confirm) {
            console.log('用户点击取消')
          } else if (res.cancel) {
            console.log('用户点击放弃提交')
            that.setData({
              isShowVerifyWindow: false
            })
           
          }
        }
      })
      
    },
    //点击  开始质询或者提交
    comfirmVerifyWindow(e) {
      return new Promise((resolve, reject) => {
        let imgUrl = []
        if(e.detail.length!==0){
          this.data.imgArr = e.detail
        }
        for(let i in this.data.imgArr){
          imgUrl.push(this.data.imgArr[i].fileId)
        }
        // 点击开始咨询埋点
        let winFrom = this.data.winFrom
        let infromWay = this.data.type==='onLine'? 'IM':'虚拟号呼叫'
        gioKeyuanLog('clickInformStart',winFrom,infromWay)


        api.submitVerifiedInfo({toUserId: this.data.userId,imgUrl,}, (res) => {
          if (res.data && res.data.isSuccess) {
            this.getCardInfo().then(()=>{
              if(this.data.type==='onLine'){ //去im聊天
                let unionid = this.data.unionid
                let cooperationId = this.data.cooperationId
                let agentId = this.data.userId
                wx.navigateTo({
                  url: `/pages/im/imMessagelist/imMessagelist?unionid=${unionid}&cooperationId=${cooperationId}&agentId=${agentId}&ispop=1`
                });
                this.setData({
                  isShowVerifyWindow: false
                })
              } else { //打开虚拟号弹窗
                let options = {
                  cooperationId:this.data.cooperationId,
                  unionid: this.data.unionid,
                  ispop:'1',
                  agentId:this.data.userId
                }
                this.$sendAuthCard(options)
                this.setData({
                  isShowVmPhone: true,
                  isShowVerifyWindow: false
                })
              }
            })
            resolve()
          }
        })
      })

    },

    // im聊天需要的数据
    getCardInfo(){
      return new Promise((resolve, reject)=>{
        this.getWxLocationBe()
        .then((res) => {
          this.setData({
            lng: res.longitude,
            lat: res.latitude
          })
          let {lng,lat} = this.data
          api.getCardInfo({lng,lat},(res)=>{
            if(res&&res.data&&res.data.isSuccess){
              let content = res.data.content
              if(content.addr.city==content.addr.province){ //为了区别xx省和xx市同名
                content.address = content.addr.city+content.addr.district+content.addr.address_reference_town_title+content.addr.address_reference_street_title
              } else {
                content.address = content.addr.province+content.addr.city+content.addr.district+content.addr.address_reference_town_title+content.addr.address_reference_street_title
              }
              setData('authCardInfo', {
                cooperationId: this.data.cooperationId,
                agentId: content.userId,
                files: content.files,
                nickname:  content.nickname,
                address: content.address,
              })

              resolve()
            } else {
              console.log('接口错误')
              reject()
            }
          })
        })
        .catch((err) => {
          console.log(err)
        })
      })
    },

    // 关闭打电话弹窗
    handleVmVisible() {
      this.setData({
        isShowVmPhone: false
      });
    },
  }
})